﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MShop.Core.Domain;
using MShop.Web.Models;
using MShop.Web.Components.Paging;
using MShop.Core.DataAccess;
using MShop.Core.Extensions;
using MShop.Core.Service.Membership;

namespace MShop.Web.Areas.Admin.Controllers
{

  
    public class AccountController : SecureController
    { 

        private readonly ICommonDao<aspnet_Users> _CommonDao;
        private readonly ICommonDao<aspnet_Roles> _CommonDao2;
        private readonly ICommonDao<ShopUsersCryptography> _CommonDao3;
        private readonly ICommonDao<ShopUsers> _CommonShopUsers;
        private readonly IRoleService _RoleService;
        public AccountController(ICommonDao<aspnet_Users> commonDao,ICommonDao<aspnet_Roles> commonDao2,ICommonDao<ShopUsers> commonShopUsers,
            IRoleService roleService,ICommonDao<ShopUsersCryptography> commonDao3)
        {
            _CommonDao = commonDao;
            _CommonDao2 = commonDao2;
            _CommonShopUsers = commonShopUsers;
            _RoleService = roleService;
            _CommonDao3 = commonDao3;
         
        }

        [Authorize]
        public ActionResult ResetPassword(Guid id)
        {
            var user = _CommonDao.FirstOrDefault(x=>x.UserId==id);
            return View(user);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ResetPassword(Guid userid, string newpassword)
        {
            var user = _CommonDao.Find(x => x.UserId == userid).First();
            if (string.IsNullOrEmpty(newpassword))
            {
                this.ModelState.AddModelError("newpassword", "新密码不能为空");

                return View(user);
            }

            MembershipUser muser = Membership.GetUser(user.UserName);
            string temppassword = muser.ResetPassword();
            muser.ChangePassword(temppassword, newpassword);
            if (Request.Params["ReturnUrl"] != null)
            {
                return Redirect(Request.Params["ReturnUrl"]);
            }
            return RedirectToAction("Index","shopusers");
        }
        [Authorize]
        public ActionResult Index(int? page,string key)
        {

            IQueryable<aspnet_Users> query = _CommonDao.Find(x => _RoleService.PowersRoleId.Contains((Guid)x.ShopUsers.RoleId));
             int pageIndex=0;
            int pageSize=30;
             if(page.HasValue) pageIndex= page.Value -1;
             if(!string.IsNullOrEmpty(key))
             {
                 query = query.Where(x=>x.UserName.Contains(key));
             }
             query = query.OrderByDescending(x => x.LastActivityDate);
             PagedList<MShop.Core.Domain.aspnet_Users> pagedList = new PagedList<aspnet_Users>(query, pageIndex, pageSize);
             return View(pagedList);
        }

        [Authorize]
        public ActionResult Delete(Guid id)
        {
            Membership.DeleteUser(Membership.GetUser(id).UserName,true);
            return RedirectToAction("index");
        }

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            base.Initialize(requestContext);
        }

       

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }


        [HttpGet]
        public ActionResult ModifyUser(Guid id)
        {
            aspnet_Users user = _CommonDao.Find(x => x.UserId == id).First();
            //ViewData["list"] = DataAccessUtil.GetSortDepartments(false,user.ShopUsers.DeptId);
            string[] roles= Roles.GetRolesForUser(user.UserName);
            ViewData["roles"] = _RoleService.FindPowerRoles().ConvertListItem("rolename", "rolename", roles);
          
            return View(user);
        }


        [HttpPost]
        public ActionResult ModifyUser(Guid id, string email, int? departmentid, string roleid)
        {
            MembershipUser user = Membership.GetUser(id);
            user.Email = email;
            ShopUsers u = _CommonShopUsers.Find(x => x.UserId == id).FirstOrDefault();
            if (u != null)
            {
                u.DeptId = departmentid;
            }
            else
            {
                u = new ShopUsers() { DeptId = departmentid, UserId = id };
                _CommonShopUsers.Save(u);
            }
             string roleName = Request.Params["roleid"];
            _RoleService.UpdateUserRole(user.UserName,roleName);
            u.RoleId = _CommonDao2.FirstOrDefault(x => x.RoleName == roleName).RoleId;
            _CommonShopUsers.SaveChanges();

            return RedirectToAction("Index");
        }

        [Authorize]
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            //ViewData["list"] = DataAccessUtil.GetSortDepartments();
            var roles = _RoleService.FindPowerRoles().ConvertListItem("rolename", "rolename");
            if (roles.Count > 0)
            {
                roles[0].Selected = true;
                ViewData["roles"] = roles;
            }
            else
            {
                ViewData["roles"] = roles;
            }
          
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
               

                if (createStatus == MembershipCreateStatus.Success)
                { 
                    aspnet_Users user = _CommonDao.Find(x => x.UserName == model.UserName).First();
                    ShopUsers faouser = new ShopUsers();
                    faouser.DeptId = model.DepartMentId;
                    faouser.UserId = user.UserId;
                    ShopUsersCryptography crypt = new ShopUsersCryptography();
                    crypt.UserId = user.UserId;
                    crypt.Balance = 0;
                    crypt.Point = 0;                    
                    _CommonShopUsers.Save(faouser);
                    _CommonDao3.Save(crypt);
                    _CommonShopUsers.SaveChanges(); 
                    Roles.AddUserToRole(model.UserName, Request.Params["roleid"]); 
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }
           // ViewData["list"] = DataAccessUtil.GetSortDepartments();
            var roles = _RoleService.FindPowerRoles().ConvertListItem("rolename", "rolename");
            ViewData["roles"] = roles;
            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "旧密码错误！");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************
        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
